<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right" class="marginTop">
      <el-breadcrumb-item >用户管理</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card class="marginTop">
      <el-row type="flex" justify="center">
        <el-col :span="4">
          <el-button type="primary" @click="addUser">添加用户</el-button>
        </el-col>
        <el-col :span="4" >
          <el-button type="primary" @click="toManage">返回至厅店管理</el-button>
        </el-col>
      </el-row>

      <!-- table表格区域 -->
      <el-table :data="List" border stripe style="width: 100%" class="marginTop">
        <!-- 展开行 -->
        <el-table-column type="expand">
          <template slot-scope="props">
            <!-- {{scope.row}} -->
            <el-form label-position="left" inline class="demo-table-expand">
              <el-form-item label="id">
                <span>{{ props.row.id }}</span>
              </el-form-item>
              <el-form-item label="姓名">
                <span>{{ props.row.name }}</span>
              </el-form-item>
              <el-form-item label="证件号">
                <span>{{ props.row.number }}</span>
              </el-form-item>
              <el-form-item label="联系方式">
                <span>{{ props.row.phone }}</span>
              </el-form-item>
              <el-form-item label="时间">
                <span>{{ props.row.time }}</span>
              </el-form-item>
              <el-form-item label="sid">
                <span>{{ props.row.sid }}</span>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="姓名" prop="name"></el-table-column>
        <el-table-column label="证件号" prop="number" width="200px"></el-table-column>
        <el-table-column label="联系方式" prop="phone" width="200px"></el-table-column>
        <el-table-column label="创建时间" prop="time" width="200px"></el-table-column>
        <el-table-column fixed="right" label="操作" width="230px">
          <template slot-scope="scope">
            <el-button size="small" type="primary" icon="el-icon-edit" @click="edit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" icon="el-icon-delete" @click="dele(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <!-- size-change 每页显示条数发生变化 -->
      <!-- current-change 页码发生变化 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNum"
        :page-sizes="[1, 2, 3, 4]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        background
      >
      </el-pagination>
    </el-card>


    <!-- 添加新用户 -->
    <el-dialog title="添加新用户" :visible.sync="userDialogVisible" width="40%"  @close="userDialogClose">
      <el-form :model="addNewuser" :rules="Rules" ref="addRef" label-width="100px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="addNewuser.name"></el-input>
        </el-form-item>
        <el-form-item label="联系方式" prop="phone">
          <el-input v-model="addNewuser.phone"></el-input>
        </el-form-item>
        <el-form-item label="身份证号码" prop="number">
          <el-input v-model="addNewuser.number"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="DialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitInfo">确 定</el-button>
      </span>
    </el-dialog>

<!--    修改用户-->
    <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="40%"  @close="editDialogClose">
      <el-form :model="editUser" :rules="Rules" ref="editRef" label-width="100px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="editUser.name"></el-input>
        </el-form-item>
        <el-form-item label="联系方式" prop="phone">
          <el-input v-model="editUser.phone"></el-input>
        </el-form-item>
        <el-form-item label="身份证号码" prop="number">
          <el-input v-model="editUser.number"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="DialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEditInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    name: "user",
    data() {
      return {
        // 查询参数
        pageNum: 1, //页码
        pageSize: 2, //每页显示条数
        // 厅店列表
        List:[],
        //添加新厅店数据
        addNewuser:{
          name:'',
          phone:'',
          number:''
        },
        editUser:{
          name:'',
          phone:'',
          number:''
        },
        editId:null,
        // 总数据条数
        total:0,
        // 控制编辑商品对话框是否显示
        userDialogVisible:false,
        editDialogVisible:false,
        // 编辑对话框的表单验证规则
        Rules:{
          name: [
            {
              required: true,
              validator: (rule, value, callback) => {
                const realnameReg = /^([a-zA-Z0-9\u4e00-\u9fa5\·]{1,10})$/
                if (!value) {
                  return callback(new Error('真实姓名不能为空!!'))
                }
                setTimeout(() => {
                  if (!realnameReg.test(value)) {
                    return callback(new Error('您的真实姓名格式错误,请输入英文或汉字!'))
                  } else {
                    callback()
                  }
                }, 100)
              },
              message: "",
              trigger: "change"
            }
          ],
          number: [
            {
              required: true,
              validator: (rule, value, callback) => {
                if (value) {
                  if (value.length == 18) {
                    if ((/^[1-9]\d{5}(19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/).test(value) == false) {
                      callback(new Error("身份证格式不正确"));
                    } else {
                      callback();
                    }
                  } else {
                    callback(new Error("身份证格式不正确"));
                  }
                } else {
                  callback(new Error("身份证号码不能为空"));
                }
              },
              message: "身份证号格式不正确",
              trigger: "change"
            }
          ],
          phone: [
            { required: true, message: '请输入电话号码', trigger: 'change' },
            {
              pattern: /^1[23456789]\d{9}$/,
              message: "电话号码格式不对",
              trigger: "change"
            }
          ]
        }
      };
    },
    mounted() {
      this.getInfoList();
    },
    methods: {
      // 根据分页获取对应的数据
      async getInfoList() {
        let sid = window.sessionStorage.getItem('sid')
        console.log('id',sid)
        let { data: res } = await this.$http.get("/agent/client/"+sid, {
          params: {
            pageNum: this.pageNum,
            pageSize: this.pageSize
          }
        });
        // 获取失败
        // if (res.meta.status !== 200) {
        //   return this.$message.error({
        //     message: res.meta.msg,
        //     duration: 1500,
        //   });
        // }
        this.total = res.data.total
        this.List = res.data.list
        console.log('用户数据：',res.data.list);
      },
      // 每页显示条数发生变化
      handleSizeChange(newSize){
        this.pageSize = newSize
        this.getInfoList()
      },
      // 页码发生变化
      handleCurrentChange(newPage){
        this.pageNum = newPage
        this.getInfoList()
      },
      addUser(){
        this.userDialogVisible=true
      },
      edit(user){
        this.editDialogVisible=true
        this.editId=user.id;
        this.editUser.name=user.name
        this.editUser.number=user.number
        this.editUser.phone=user.phone
      },
      async dele(user){
        let result = await this.$confirm('此操作将永久删除该用户?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(reason => reason)

        // 取消删除
        if(result === 'cancel'){
          return this.$message({
            message:'已取消删除',
            duration:2000
          })
        }
        let {data:res} = await this.$http.delete('/agent/client/'+user.id)
        // 修改失败
        if (res.code !== 200) {
          return this.$message.error({
            message: res.message,
            duration: 2000,
          });
        }

        this.$message.success({
          message:res.data,
          duration: 2000
        })
        this.getInfoList()
      },
      toManage(){
        this.$router.push('/manage')
      },
      // // 编辑对话框关闭
      userDialogClose(){
        this.$refs.addRef.resetFields()
      },
      editDialogClose(){
        this.$refs.addRef.resetFields()
      },
      //添加新用户
      submitInfo(){
        this.$refs.addRef.validate(async (valid,options) =>{
          // 表单验证未通过
          if(!valid){
            let arr = Object.keys(options)
            return this.$message.error({
              message: options[arr[0]][0].message,
              duration: 1500
            })
          }
          console.log(this.addNewuser);
          this.addNewuser.time=new Date().getTime();
          const {data:res} = await this.$http.post('/agent/client/'+window.sessionStorage.getItem('sid'),this.addNewuser)

          if (res.code !== 200) {
            return this.$message.error({
              message: res.message,
              duration: 2000,
            });
          }

          this.$message.success({
            message:res.data,
            duration: 2000
          })
          this.getInfoList()
          this.userDialogVisible = false
        })
      },
      submitEditInfo(){
        this.$refs.editRef.validate(async (valid,options) =>{
          // 表单验证未通过
          if(!valid){
            let arr = Object.keys(options)
            return this.$message.error({
              message: options[arr[0]][0].message,
              duration: 2000
            })
          }
          console.log(this.editUser);
          const {data:res} = await this.$http.put('/agent/client/'+this.editId,this.editUser)
          // 修改失败
          if (res.code !== 200) {
            return this.$message.error({
              message: res.message,
              duration: 2000,
            });
          }

          this.$message.success({
            message:res.data,
            duration: 2000
          })
          this.getInfoList()
          this.editDialogVisible = false
        })
      }
    }
  };
</script>

<style lang="less">
  .demo-table-expand {
    font-size: 0;
  }
  .demo-table-expand label {
    width: 120px;
    color: #99a9bf;
  }
  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 80%;
  }
  .marginTop{
    margin-top: 10px;
  }
</style>
